package org.xg.study.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author CMG
 * @version 1.0
 * @description
 * @cLassName MyServlet
 * @date 2021/9/23 10:39
 **/
@WebServlet("/myLife")
public class MyServletLC extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private int initCount = 0;
    private int httpCount = 0;
    private int destroyCount = 0;

    @Override
    public void destroy() {
        destroyCount++;
        super.destroy();
        //向控制台输出destroy方法被调用次数
        System.out.println("***********************destroy方法：" + destroyCount + "****************");
    }

    @Override
    public void init() throws ServletException {
        initCount++;
        super.init();
        //向控制台输出init方法被调用次数
        System.out.println("init方法：" + initCount);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        httpCount++;
        //向控制台输出doGet方法次数
        System.out.println("doGet方法：" + httpCount);
        // 设置响应给页面的格式、字符集
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        //向页面输出
        writer.write("初始化次数：" + initCount + "<br/>" + "处理请求次数：" + httpCount + "<br/>" + "销毁次数：" + destroyCount);
        writer.close();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
